<!-- 分组教学 -->
<template>
	<pannel hasHeader hasFooter @reback="reback">
		<div slot="header" class="header">
			<span class="class">{{ formData.className }}</span>
			<span style="margin-left: 40px">
				在线人数：
				<span class="hasBindValue">{{ bindStudentNum }}</span>
				/{{ studentList.length }}
			</span>
			<span style="margin-left: 40px" v-if="machineData.machId">
				接收器{{ machineData.machId }}：
				<span :class="[machineData.online == 1 ? 'connect' : 'no-connect']">{{
					machineData.online == 1 ? '已连接' : '未连接'
				}}</span>
			</span>
		</div>
		<div class="flex flex-wrap">
			<div class="group-item" v-for="(group, gindex) in groupList">
				<div class="group-item-title">
					<!-- <a-checkbox :checked="group.isCheckAll" @change="(e) => onChangeAll(e, gindex)"> -->
					<span>{{ group.groupName }}</span>
					<!-- </a-checkbox> -->
				</div>
				<!-- <a-checkbox-group :value="group.checklist" @change="(e) => onChange(e, gindex)"> -->
				<a-row>
					<a-col :span="24" v-for="(item, index) in group.list" :key="index" class="group-item-name">
						<!-- <a-checkbox :value="item.studId"> -->
						<span>
							{{ item.studName }}
						</span>
						<!-- </a-checkbox> -->
					</a-col>
				</a-row>
				<!-- </a-checkbox-group> -->
			</div>
		</div>
		<div class="right-tabs">
			<div class="tab" :class="[{ blue: opType == 'random' }]" @click="skipPage('random')">随机分组</div>
			<div class="tab" :class="[{ blue: opType == 'import' }]" @click="skipPage('import')">导入分组</div>
		</div>
		<div slot="footer" class="conbox-ft">
			<template v-if="opType == 'random'">
				<div class="setUserNums">
					<div class="flex flex-align-center flex-pack-justify" style="margin-top: 10px">
						<span class="setUserNums-title">分组个数</span>
						<div class="setUserNums-input">
							<a-input-number v-model="count" :min="1" :max="15" />
						</div>
						<span class="num"
							>最大可以选择{{ studentList.length > 15 ? 15 : studentList.length }}个分组</span
						>
					</div>
				</div>
				<div class="ft-btn save-btn" @click="startGroup">
					{{ groupList.length > 0 ? '重新分组' : '开始分组' }}
				</div>
			</template>
			<template v-else>
				<div class="flex flex-pack-center">
					<div>
						<a-upload
							name="file"
							:beforeUpload="beforeUpload"
							:showUploadList="false"
							accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
						>
							<div class="ft-btn save-btn">
								<a-icon type="upload" />
								上传文件
							</div>
						</a-upload>
						<div>{{ filename }}</div>
					</div>
					<a
						style="
							position: absolute;
							left: 50%;
							transform: translateX(-400px);
							top: 10px;
							font-size: 20px;
							height: auto;
							padding: 12px 30px;
						"
						href="javascript:;"
						class="ant-btn"
						@click="downGroupTempl"
					>
						<a-icon type="download" />
						<span>模板下载</span>
					</a>
				</div>
			</template>
		</div>
	</pannel>
</template>

<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex';
import bus from '@/utils/eventBus';
import { debounce } from '@/utils/base.js';
import praiseModal from '../module/praiseModal.vue';
import pannel from './pannel.vue';
import { postActionExport, sysManageapi, postActionUpload } from '@/api/index.js';
/*
 *
 * 解决数组中对象随机分组问题
 * list:要分组的数组
 * num:分成的组数
 * */
function changelist(list, num) {
	console.log(list, num);
	var n = list.length - 1; //获取数组下标的上限
	var length = n / num; //获取分组后单组的长度
	var list1 = list,
		list2 = new Array(num);
	console.log(n, length);
	do {
		for (var i = 0; i < num; i++) {
			var id = Math.ceil(Math.random(0, list1.length - 1) * list1.length - 1); //获取下标范围内的随机数
			if (list1[id]) {
				console.log('到这里了吗');
				if (list2[i] && list2[i].list && list2[i].list.length > 0) {
					console.log('到这里了吗2');
					list2[i].list.push(list1[id]); //将获取的对象放入定义的变量数组中
				} else {
					list2[i] = {
						isCheckAll: false,
						list: [list1[id]],
						checklist: [],
						groupName: '第' + (i + 1) + '小组',
					};
				}

				list1.splice(id, 1);
			}
		}
	} while (list1.length > 0);

	return list2;
}
export default {
	name: 'group',
	components: { praiseModal, pannel },
	props: {
		//接收器信息
		machineData: {
			type: Object,
			default: () => {},
		},
		//表单数据
		formData: {
			type: Object,
			default: () => {},
		},
	},
	data() {
		return {
			csId: '',
			groupList: [],
			count: 2,
			opType: 'random',
			filename: '',
		};
	},
	created() {
		let beginClassData = this.$ls.get('beginClass'); //上课数据
		this.csId = beginClassData.csId;
		this.getGroupList();
	},
	watch: {
		studentList: {
			handler(newValue, oldValue) {
				//监听学生名单，状态变化，同步给后端
				if (JSON.stringify(newValue) != JSON.stringify(oldValue) && newValue.length > 0) {
					this.getGroupList();
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
	},
	computed: {
		...mapState({
			deviceType: (state) => state.websockStore.deviceType,
			studentList: (state) => state.websockStore.studentList,
			stopDeviceEventList: (state) => state.websockStore.stopDeviceEventList,
			isPro: (state) => state.isPro,
		}),
		selectStudList() {
			let studList = [];
			this.groupList.forEach((item) => {
				studList = studList.concat(item.checklist);
			});
			return studList;
		}, //绑定学生人数
		bindStudentNum() {
			let list = this.studentList.filter((item) => item.status == '1');
			return this.machineData && this.machineData.online == 1 ? list.length : 0;
		},
	},

	methods: {
		...mapMutations(['WEBSOCKET_SEND', 'SET_studentList', 'SET_STOPDEVICEEVENTLIST']),
		startGroup() {
			let list = JSON.parse(JSON.stringify(this.studentList));
			this.groupList = changelist(list, this.count);
			console.log('this.groupList', this.groupList);
			this.saveGroup(this.groupList);
		},
		//保存分组
		saveGroup(list) {
			let groups = [];
			list.forEach((item, index) => {
				if (item && item.list.length > 0) {
					groups.push({
						groupName: '第' + (index + 1) + '小组',
						studIds: item.list.filter((item) => !!item).map((item) => item.studId),
					});
				}
			});
			let param = {
				classId: this.formData.classId,
				subjectCode: this.formData.subjectCode,
				groups,
			};
			this.$postAction(this.$sysManageapi.answerUrl.addGroup, param);
		},
		getGroupList() {
			this.$postAction(this.$sysManageapi.answerUrl.getGroupList, {
				classId: this.formData.classId,
				subjectCode: this.formData.subjectCode,
				opType: this.opType == 'random' ? 1 : 2,
			}).then((da) => {
				console.log('daozhelilema', da);
				let list = [];
				if (da.data && da.data.groups && da.data.groups.length > 0) {
					da.data.groups.forEach((item, index) => {
						let studIds = item.studIds;
						studIds.forEach((studId) => {
							let studInfo = this.studentList.find((sitem) => sitem.studId == studId);
							console.log('studInfo', studInfo, studId);
							if (studInfo) {
								if (!list[index]) {
									list[index] = {
										isCheckAll: false,
										list: [studInfo],
										checklist: [],
										groupName: item.groupName,
									};
								} else {
									list[index].list.push(studInfo);
								}
							}
						});
					});
					console.log('list', list);
				}
				this.groupList = list;
			});
		},
		//返回
		reback() {
			/* 判断是否已经停止签到*/
			this.$emit('checkMenu', { type: 'group' });
		},
		onChangeAll(e, gindex) {
			this.groupList[gindex].isCheckAll = e.target.checked;
			this.groupList[gindex].checklist = e.target.checked
				? this.groupList[gindex].list.map((item, index) => item.studId)
				: [];
		},
		onChange(e, gindex) {
			console.log('e', e);
			this.groupList[gindex].checklist = e;
			console.log('e', e, this.groupList[gindex].checklist.length, this.groupList[gindex].list.length);

			if (this.groupList[gindex].checklist.length == this.groupList[gindex].list.length) {
				this.groupList[gindex].isCheckAll = true;
			} else {
				this.groupList[gindex].isCheckAll = false;
			}
		},
		skipPage(opType) {
			this.opType = opType;
			this.filename = '';
			this.getGroupList();
		},
		beforeUpload(file) {
			this.importFile(file);
			return false;
		},
		normFile(e) {
			if (Array.isArray(e)) {
				return e;
			}
			this.filename = e.file.name;
			return e && e.file;
		},
		importFile(file) {
			// this.confirmLoading = true;
			const formData = new FormData();

			formData.append('file', file);
			formData.append('classId', this.formData.classId);
			formData.append('subjectCode', this.formData.subjectCode);

			postActionUpload(sysManageapi.answerUrl.uploadGroup, formData)
				.then((res) => {
					if (res.code == 1) {
						// this.confirmLoading = false;
						this.$message.success('导入成功');
						this.filename = '';
						this.getGroupList();
					}
				})
				.finally(() => {
					// this.confirmLoading = false;
				});
		},
		downGroupTempl() {
			this.$postActionExport(
				this.$sysManageapi.answerUrl.downGroupTempl + '?classId=' + this.formData.classId
			).then((res) => {
				let BlobFile = res;
				let fileName = 'group.xlsx';
				console.log(BlobFile);
				let blobObject = new Blob([BlobFile], {
					//type: 'application/vnd.ms-excel,charset=utf-8',
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
				}); //如果是字节流
				//是IE浏览器
				if (!!window.ActiveXObject || 'ActiveXObject' in window) {
					window.navigator.msSaveOrOpenBlob(blobObject, fileName);
				} else {
					//火狐谷歌都兼容
					//模板中要有一个预定义好的a标签
					var link = document.createElement('a');
					link.href = window.URL.createObjectURL(blobObject); //如果是字节流
					//link.href = BlobFile;
					link.target = '_blank';
					link.download = fileName;
					link.click();
					//释放内存
					window.URL.revokeObjectURL(link.href);
				}
				this.$message.success('导出成功');
			});
		},
	},
};
</script>

<style lang="less" scoped>
.header {
	font-size: 22px;
	color: #fff;
	text-align: center;
	width: 100%;
	.class {
		letter-spacing: -1px;
	}

	.sign {
		margin: 0 40px;
	}

	.hasBindValue {
		color: @warning-color;
	}

	.no-connect {
		color: @warning-color;
	}

	.connect {
		color: #fff;
	}
}
.group-item {
	width: 160px;
	margin: 10px;
	border: 1px solid @primary-color;
	border-radius: 10px;
	overflow: hidden;
	line-height: 30px;
	color: #666;
	font-size: 20px;
	.group-item-title {
		background: #f3f8ff;
		color: #fff;
		padding: 0 16px;
		font-size: 24px;
		line-height: 50px;
		border-bottom: 1px solid @primary-color;
		span {
			font-size: 24px;
			color: @primary-color;
		}
	}
	.group-item-name {
		padding: 6px 16px;
	}
	.group-item-name span {
		font-size: 20px;
	}
}

.praisebar {
	position: absolute;
	bottom: 40px;
	left: 50%;
	transform: translateX(-50%);
	font-size: 18px;
	.praiselist {
		text-decoration: underline;
		color: @primary-color;
		margin-left: 20px;
	}
}
/deep/ .ant-checkbox-wrapper {
	display: flex;
	align-items: center;
	.ant-checkbox {
		top: 0 !important;
	}
	.ant-checkbox + span {
		flex: 1;
		min-width: 0;
		span {
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			width: 100%;
			display: block;
		}
	}
}

/* 主体内容右侧tab */
.right-tabs {
	position: absolute;
	left: calc(100% - 148px);
	bottom: 35px;
	background: @primary-color;
	width: 123px;
	padding: 2px 6px 2px 2px;
	color: #4d5053;
	font-size: 22px;
	font-weight: bold;
	.tab {
		background: #fff;
		text-align: center;
		cursor: pointer;
		&.blue {
			background: none;
			color: #fff;
		}
	}
}

.conbox-ft {
	position: relative;
	z-index: 999;
	.save-btn {
		background: @primary-color;
		margin: 0 auto;
		width: 300px;
		height: 60px;
		line-height: 60px;
		text-align: center;
		color: #fff;
		font-size: 30px;
		font-weight: bold;
		border-radius: 40px;
		cursor: pointer;
		&.red {
			background: #e64343;
			border-color: rgba(230, 67, 67, 0.5);
		}
	}
	.save-btn.disabeld {
		background: #becad4;
	}
	@media screen and (max-width: 1366px) {
		width: 1024px;
	}
}

/deep/.setUserNums {
	position: absolute;
	left: 10px;
	.setUserNums-input {
		border: 1px solid @primary-color;
		border-radius: 23px;
		margin-left: 10px;
		input,
		.ant-input-number {
			border: none;
			height: 38px;
			border-radius: 23px;
			font-size: 15px;
			font-weight: bold;
			width: 140px;
		}
		.ant-input-number-handler-wrap {
			border-radius: 0 23px 23px 0 !important;
		}
		.ant-select-selection {
			border: none;
			height: 38px;
			border-radius: 23px;
			font-size: 15px;
		}

		.ant-select-selection__rendered {
			line-height: 38px;
		}
	}

	.num {
		color: #f00;
		font-size: 16px;
		margin-left: 10px;
	}
	.setUserNums-title {
		left: -5em;
		color: #000;
		font-size: 16px;
	}
}
.uploadBtn {
	position: absolute;
	right: 0;
	top: 50%;
	transform: translateY(-50%);
}
</style>
